// utils/exportShippingOrder.js
import ExcelJS from 'exceljs'
import { saveAs } from 'file-saver'

/**
 * 导出发货单到Excel
 * @param {Object} sendInfo - 发货单信息
 */
export const exportShippingOrderToExcel = async (sendInfo) => {
  try {
    const workbook = new ExcelJS.Workbook()
    const worksheet = workbook.addWorksheet('发货单')

    // 设置页面打印选项
    worksheet.pageSetup = {
      paperSize: 9, // A4
      orientation: 'portrait',
      margins: { left: 0.7, right: 0.7, top: 0.75, bottom: 0.75, header: 0.3, footer: 0.3 },
    }

    // 设置默认列宽
    worksheet.columns = [
      { key: 'col1', width: 12 },
      { key: 'col2', width: 20 },
      { key: 'col3', width: 15 },
      { key: 'col4', width: 12 },
      { key: 'col5', width: 15 },
      { key: 'col6', width: 25 },
      { key: 'col7', width: 15 },
      { key: 'col8', width: 15 },
    ]

    let currentRow = 1

    // 1. 标题部分
    currentRow = addTitle(worksheet, currentRow)

    // 2. 基本信息部分
    currentRow = addBasicInfo(worksheet, sendInfo, currentRow)

    // 3. 收货人信息部分
    currentRow = addRecipientInfo(worksheet, sendInfo, currentRow)

    // 4. 商品清单部分
    currentRow = addProductList(worksheet, sendInfo, currentRow)

    // 5. 物流信息部分
    currentRow = addLogisticsInfo(worksheet, sendInfo, currentRow)

    // 6. 备注部分
    currentRow = addNotes(worksheet, sendInfo, currentRow)

    // 7. 签字确认部分
    addSignature(worksheet, currentRow)

    // 设置整个表格的边框
    setAllBorders(worksheet, currentRow)

    // 导出文件
    const fileName = `发货单_${sendInfo.sendNo}_${formatDate(new Date())}.xlsx`
    const buffer = await workbook.xlsx.writeBuffer()
    saveAs(new Blob([buffer]), fileName)
    return true
  } catch (error) {
    console.error('导出发货单失败:', error)
    throw new Error('导出发货单失败，请重试')
  }
}

/**
 * 添加标题
 */
const addTitle = (worksheet, startRow) => {
  // 标题行
  const titleRow = worksheet.getRow(startRow)
  titleRow.height = 40
  titleRow.getCell(1).value = '发  货  单'

  // 合并标题单元格 (A列到H列)
  worksheet.mergeCells(startRow, 1, startRow, 8)

  // 设置标题样式
  const titleCell = worksheet.getCell(startRow, 1)
  titleCell.font = {
    name: '黑体',
    size: 20,
    bold: true,
  }
  titleCell.alignment = {
    vertical: 'middle',
    horizontal: 'center',
  }
  titleCell.fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: 'FFE6F3FF' },
  }

  return startRow + 2 // 标题后空一行
}

/**
 * 添加基本信息
 */
const addBasicInfo = (worksheet, sendInfo, startRow) => {
  // 基本信息标题
  const infoTitleRow = worksheet.getRow(startRow)
  infoTitleRow.height = 25
  infoTitleRow.getCell(1).value = '基本信息'

  worksheet.mergeCells(startRow, 1, startRow, 2)
  const infoTitleCell = worksheet.getCell(startRow, 1)
  infoTitleCell.font = { name: '微软雅黑', size: 12, bold: true }
  infoTitleCell.alignment = { vertical: 'middle', horizontal: 'left' }
  infoTitleCell.fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: 'FFF0F0F0' },
  }

  let row = startRow + 1

  // 第一行：发货单号、发货日期
  worksheet.getRow(row).height = 22
  worksheet.getCell(row, 1).value = '发货单号：'
  worksheet.getCell(row, 2).value = sendInfo.sendNo || ''
  worksheet.getCell(row, 4).value = '发货日期：'
  worksheet.getCell(row, 5).value = formatDateTime(sendInfo.sendTime)

  // 合并单元格
  worksheet.mergeCells(row, 2, row, 3)
  worksheet.mergeCells(row, 5, row, 6)

  row++

  // 第二行：订单号、操作员
  worksheet.getRow(row).height = 22
  worksheet.getCell(row, 1).value = '订单号：'
  worksheet.getCell(row, 2).value = sendInfo.memberOrderMId || ''
  worksheet.getCell(row, 4).value = '操作员：'
  worksheet.getCell(row, 5).value = sendInfo.dealerOperator || ''

  worksheet.mergeCells(row, 2, row, 3)
  worksheet.mergeCells(row, 5, row, 6)

  row++

  // 第三行：发货状态、打印次数
  worksheet.getRow(row).height = 22
  worksheet.getCell(row, 1).value = '发货状态：'
  worksheet.getCell(row, 2).value = getSendStatusText(sendInfo.sendState)
  worksheet.getCell(row, 4).value = '打印次数：'
  worksheet.getCell(row, 5).value = sendInfo.printNum || 0

  worksheet.mergeCells(row, 2, row, 3)
  worksheet.mergeCells(row, 5, row, 6)

  // 设置标签列样式（加粗）
  for (let r = startRow + 1; r <= row; r++) {
    ;[1, 4].forEach((col) => {
      const cell = worksheet.getCell(r, col)
      if (cell.value) {
        cell.font = { name: '微软雅黑', size: 10, bold: true }
        cell.alignment = { vertical: 'middle', horizontal: 'left' }
      }
    })
  }

  return row + 2
}

/**
 * 添加收货人信息
 */
const addRecipientInfo = (worksheet, sendInfo, startRow) => {
  // 收货人信息标题
  const recipientTitleRow = worksheet.getRow(startRow)
  recipientTitleRow.height = 25
  recipientTitleRow.getCell(1).value = '收货人信息'

  worksheet.mergeCells(startRow, 1, startRow, 2)
  const recipientTitleCell = worksheet.getCell(startRow, 1)
  recipientTitleCell.font = { name: '微软雅黑', size: 12, bold: true }
  recipientTitleCell.alignment = { vertical: 'middle', horizontal: 'left' }
  recipientTitleCell.fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: 'FFF0F0F0' },
  }

  let row = startRow + 1

  // 第一行：收货人、联系电话
  worksheet.getRow(row).height = 22
  worksheet.getCell(row, 1).value = '收货人：'
  worksheet.getCell(row, 2).value = sendInfo.consignee || ''
  worksheet.getCell(row, 4).value = '联系电话：'
  worksheet.getCell(row, 5).value = sendInfo.mobilphone || ''

  worksheet.mergeCells(row, 2, row, 3)
  worksheet.mergeCells(row, 5, row, 6)

  row++

  // 第二行：收货地址（整行）
  worksheet.getRow(row).height = 22
  worksheet.getCell(row, 1).value = '收货地址：'
  worksheet.getCell(row, 2).value = `${sendInfo.xzqhName || ''} ${sendInfo.address || ''}`

  worksheet.mergeCells(row, 2, row, 8)

  row++

  // 第三行：邮箱、固定电话
  worksheet.getRow(row).height = 22
  worksheet.getCell(row, 1).value = '邮箱：'
  worksheet.getCell(row, 2).value = sendInfo.email || ''
  worksheet.getCell(row, 4).value = '固定电话：'
  worksheet.getCell(row, 5).value = sendInfo.phone || ''

  worksheet.mergeCells(row, 2, row, 3)
  worksheet.mergeCells(row, 5, row, 6)

  // 设置标签列样式（加粗）
  for (let r = startRow + 1; r <= row; r++) {
    ;[1, 4].forEach((col) => {
      const cell = worksheet.getCell(r, col)
      if (cell.value) {
        cell.font = { name: '微软雅黑', size: 10, bold: true }
        cell.alignment = { vertical: 'middle', horizontal: 'left' }
      }
    })
  }

  return row + 2
}

/**
 * 添加商品清单
 */
const addProductList = (worksheet, sendInfo, startRow) => {
  // 商品清单标题
  const productTitleRow = worksheet.getRow(startRow)
  productTitleRow.height = 25
  productTitleRow.getCell(1).value = '商品清单'

  worksheet.mergeCells(startRow, 1, startRow, 2)
  const productTitleCell = worksheet.getCell(startRow, 1)
  productTitleCell.font = { name: '微软雅黑', size: 12, bold: true }
  productTitleCell.alignment = { vertical: 'middle', horizontal: 'left' }
  productTitleCell.fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: 'FFF0F0F0' },
  }

  let row = startRow + 1

  // 表头
  const headerRow = worksheet.getRow(row)
  headerRow.height = 25
  const headers = ['序号', '商品名称', '规格', '单位', '数量', '商品分类', '发货地址', '有效期']
  headers.forEach((header, index) => {
    const cell = headerRow.getCell(index + 1)
    cell.value = header
    cell.font = { name: '微软雅黑', size: 10, bold: true }
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFD9E2F3' },
    }
  })

  row++

  // 商品明细
  let totalQuantity = 0
  if (sendInfo.pzOrderSendDList && sendInfo.pzOrderSendDList.length > 0) {
    sendInfo.pzOrderSendDList.forEach((item, index) => {
      const quantity = item.purchaseQuantity || 0
      totalQuantity += quantity

      const itemRow = worksheet.getRow(row)
      itemRow.height = 22

      itemRow.getCell(1).value = index + 1
      itemRow.getCell(2).value = item.goodsName || ''
      itemRow.getCell(3).value = item.specifications || ''
      itemRow.getCell(4).value = item.unit || ''
      itemRow.getCell(5).value = quantity
      itemRow.getCell(6).value = item.dealerGoodsTypeName || ''
      itemRow.getCell(7).value = item.address || ''
      itemRow.getCell(8).value =
        `${formatDate(item.periodStartingDate)} ~ ${formatDate(item.periodEndDate)}`

      // 设置商品行样式
      for (let col = 1; col <= 8; col++) {
        const cell = itemRow.getCell(col)
        cell.font = { name: '微软雅黑', size: 9 }
        cell.alignment = {
          vertical: 'middle',
          horizontal: col === 1 || col === 5 ? 'center' : 'left',
          wrapText: true,
        }
      }

      row++
    })
  }

  // 合计行
  const totalRow = worksheet.getRow(row)
  totalRow.height = 25
  totalRow.getCell(1).value = '合计'
  totalRow.getCell(5).value = totalQuantity

  worksheet.mergeCells(row, 1, row, 4)

  // 设置合计行样式
  for (let col = 1; col <= 8; col++) {
    const cell = totalRow.getCell(col)
    cell.font = { name: '微软雅黑', size: 10, bold: true }
    cell.alignment = { vertical: 'middle', horizontal: 'center' }
    cell.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFFEB9C' },
    }
  }

  return row + 2
}

/**
 * 添加物流信息
 */
const addLogisticsInfo = (worksheet, sendInfo, startRow) => {
  // 物流信息标题
  const logisticsTitleRow = worksheet.getRow(startRow)
  logisticsTitleRow.height = 25
  logisticsTitleRow.getCell(1).value = '物流信息'

  worksheet.mergeCells(startRow, 1, startRow, 2)
  const logisticsTitleCell = worksheet.getCell(startRow, 1)
  logisticsTitleCell.font = { name: '微软雅黑', size: 12, bold: true }
  logisticsTitleCell.alignment = { vertical: 'middle', horizontal: 'left' }
  logisticsTitleCell.fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: 'FFF0F0F0' },
  }

  let row = startRow + 1

  // 物流信息
  const logisticsRow = worksheet.getRow(row)
  logisticsRow.height = 22
  logisticsRow.getCell(1).value = '快递公司：'
  logisticsRow.getCell(2).value =
    sendInfo.expressCompanyname || getExpressCompanyName(sendInfo.expressCompanycode)
  logisticsRow.getCell(4).value = '快递单号：'
  logisticsRow.getCell(5).value = sendInfo.trackingNumber || ''

  worksheet.mergeCells(row, 2, row, 3)
  worksheet.mergeCells(row, 5, row, 8)

  // 设置标签列样式（加粗）
  const labelCell1 = worksheet.getCell(row, 1)
  labelCell1.font = { name: '微软雅黑', size: 10, bold: true }
  labelCell1.alignment = { vertical: 'middle', horizontal: 'left' }

  const labelCell2 = worksheet.getCell(row, 4)
  labelCell2.font = { name: '微软雅黑', size: 10, bold: true }
  labelCell2.alignment = { vertical: 'middle', horizontal: 'left' }

  return row + 2
}

/**
 * 添加备注
 */
const addNotes = (worksheet, sendInfo, startRow) => {
  const notesRow = worksheet.getRow(startRow)
  notesRow.height = 40
  notesRow.getCell(1).value = '备注：'
  notesRow.getCell(2).value = sendInfo.notes || ''

  worksheet.mergeCells(startRow, 2, startRow, 8)

  // 设置样式
  const labelCell = worksheet.getCell(startRow, 1)
  labelCell.font = { name: '微软雅黑', size: 10, bold: true }
  labelCell.alignment = { vertical: 'top', horizontal: 'left' }

  const valueCell = worksheet.getCell(startRow, 2)
  valueCell.font = { name: '微软雅黑', size: 10 }
  valueCell.alignment = { vertical: 'top', horizontal: 'left', wrapText: true }

  return startRow + 2
}

/**
 * 添加签字确认
 */
const addSignature = (worksheet, startRow) => {
  const signatureRow = worksheet.getRow(startRow)
  signatureRow.height = 30

  signatureRow.getCell(1).value = '发货人签字：'
  signatureRow.getCell(3).value = '收货人签字：'
  signatureRow.getCell(6).value = '日期：'

  worksheet.mergeCells(startRow, 1, startRow, 2)
  worksheet.mergeCells(startRow, 3, startRow, 5)
  worksheet.mergeCells(startRow, 6, startRow, 8)

  // 设置样式
  for (let col = 1; col <= 8; col += 2) {
    const cell = signatureRow.getCell(col)
    cell.font = { name: '微软雅黑', size: 10, bold: true }
    cell.alignment = { vertical: 'middle', horizontal: 'left' }
  }
}

/**
 * 设置所有单元格边框
 */
const setAllBorders = (worksheet, totalRows) => {
  worksheet.eachRow((row) => {
    row.eachCell((cell) => {
      cell.border = {
        top: { style: 'thin', color: { argb: 'FF000000' } },
        left: { style: 'thin', color: { argb: 'FF000000' } },
        bottom: { style: 'thin', color: { argb: 'FF000000' } },
        right: { style: 'thin', color: { argb: 'FF000000' } },
      }

      // 默认字体和对齐方式
      if (!cell.font || (!cell.font.name && !cell.font.size)) {
        cell.font = { name: '微软雅黑', size: 10 }
      }
      if (!cell.alignment) {
        cell.alignment = { vertical: 'middle', horizontal: 'left' }
      }
    })
  })

  // 设置表格外边框（加粗）
  const borderStyle = { style: 'medium', color: { argb: 'FF000000' } }

  // 顶部边框
  for (let col = 1; col <= 8; col++) {
    const cell = worksheet.getCell(1, col)
    cell.border = {
      ...cell.border,
      top: borderStyle,
    }
  }

  // 底部边框
  for (let col = 1; col <= 8; col++) {
    const cell = worksheet.getCell(totalRows, col)
    cell.border = {
      ...cell.border,
      bottom: borderStyle,
    }
  }

  // 左边框
  for (let row = 1; row <= totalRows; row++) {
    const cell = worksheet.getCell(row, 1)
    cell.border = {
      ...cell.border,
      left: borderStyle,
    }
  }

  // 右边框
  for (let row = 1; row <= totalRows; row++) {
    const cell = worksheet.getCell(row, 8)
    cell.border = {
      ...cell.border,
      right: borderStyle,
    }
  }
}

/**
 * 格式化日期时间
 * @param {string} dateStr - 日期字符串
 * @returns {string} 格式化后的日期时间
 */
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

/**
 * 格式化日期
 * @param {string|Date} dateStr - 日期字符串或日期对象
 * @returns {string} 格式化后的日期
 */
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = dateStr instanceof Date ? dateStr : new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

/**
 * 获取发货状态文本
 * @param {number} status - 状态码
 * @returns {string} 状态文本
 */
const getSendStatusText = (status) => {
  const statusMap = {
    0: '待发货',
    1: '已发货',
    2: '已取消',
    3: '运输中',
    4: '已签收',
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取快递公司名称
 * @param {string} code - 快递公司代码
 * @returns {string} 快递公司名称
 */
const getExpressCompanyName = (code) => {
  const companyMap = {
    yuantong: '圆通快递',
    shentong: '申通快递',
    zhongtong: '中通快递',
    yunda: '韵达快递',
    shunfeng: '顺丰快递',
    debangkuaidi: '德邦快递',
    ems: 'EMS',
    jingdong: '京东快递',
  }
  return companyMap[code] || code || '未知快递'
}
